import axios, {
  AxiosInstance,
  AxiosError,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import type { App } from "vue";

const service: AxiosInstance = axios.create({
  // baseURL: "https://pokeapi.co/api/v2/",
  timeout: 5000,
});

// 请求拦截器，对请求配置进行一些处理或设置
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // console.log("[ config ] >", config);
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error: AxiosError) => {
    // console.log("err", err);
    return Promise.reject(new Error("fail" + error));
  },
);

export default service;

export const setRequest = (app: App<Element>) => {
  app.provide("$request", service);
};
